Reverse words in a string III

Time: O(N); Space: O(1); easy

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: s = “Let’s take LeetCode contest”

Output: “s’teL ekat edoCteeL tsetnoc”

Note:

  • There will not be any extra space in the string.

[3]:
class Solution1(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        def reverse(s, begin, end):
            for i in range((end - begin) // 2):
                s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]

        s, i = list(s), 0
        for j in range(len(s) + 1):
            if j == len(s) or s[j] == ' ':
                reverse(s, i, j)
                i = j + 1
        return "".join(s)
[4]:
sol = Solution1()
s = "Let's take LeetCode contest"
assert sol.reverseWords(s) == "s'teL ekat edoCteeL tsetnoc"